<template>
  <div style="margin-top: 20px">
    <ko-card :title="$t('business.access_control.role')">
      <el-row :gutter="20">
        <el-form ref="form" label-position="top" :model="roleRef">
          <el-col :span="6">
            <el-form-item :label="$t('business.configuration.kind')" required>
              <el-select
                v-model="roleRef.kind"
                style="width: 100%"
                @change="onRoleRefKindChanged(roleRef.kind)"
              >
                <el-option label="ClusterRole" :value="'ClusterRole'" />
                <el-option v-if="namespace" label="Role" :value="'Role'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="$t('business.configuration.name')" required>
              <el-select v-model="roleRef.name" style="width: 100%">
                <el-option
                  v-for="(role, index) in roles"
                  :key="index"
                  :label="role.metadata.name"
                  :value="role.metadata.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
    </ko-card>
    <div style="margin-top: 10px">
      <ko-card :title="$t('business.access_control.object')">
        <el-form ref="form" label-position="top" :model="editForm">
          <el-card
            v-for="(row, ind) in editForm.subjects"
            v-bind:key="ind"
            style="
              background-color: #292a2e;
              margin-top: 10px;
              position: relative;
            "
          >
            <div
              style="
                float: right;
                padding: 3px 0;
                position: relative;
                z-index: 1;
              "
            >
              <el-button type="text" @click="onRemoveSubject(ind)"
                >{{ $t("commons.button.delete") }}
              </el-button>
            </div>
            <div>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item
                    :label="$t('business.configuration.kind')"
                    prop="kind"
                  >
                    <el-select
                      v-model="row.kind"
                      style="width: 100%"
                      @change="onSubjectKindChanged(row)"
                    >
                      <el-option label="User" :value="'User'" />
                      <el-option label="Group" :value="'Group'" />
                      <el-option
                        label="ServiceAccount"
                        :value="'ServiceAccount'"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <div v-if="row.kind === 'ServiceAccount'">
                  <el-col :span="6">
                    <el-form-item
                      :label="$t('business.namespace.namespace')"
                      prop="namespace"
                    >
                      <el-select
                        v-model="row.namespace"
                        @change="onNamespaceChange(row, ind)"
                      >
                        <el-option
                          v-for="namespace in namespaces"
                          :key="namespace"
                          :label="namespace"
                          :value="namespace"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="ServiceAccount" prop="serviceAccount">
                      <el-select v-model="row.name" v-loading="loading">
                        <el-option
                          v-for="item in serviceAccountList[ind]"
                          :key="item.metadata.name"
                          :label="item.metadata.name"
                          :value="item.metadata.name"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </div>
                <div v-else>
                  <el-col :span="6">
                    <el-form-item :label="$t('commons.table.name')" prop="name">
                      <el-input v-model="row.name" />
                    </el-form-item>
                  </el-col>
                </div>
              </el-row>
            </div>
          </el-card>
        </el-form>
        <el-button style="margin-top: 10px" @click="onAddSubject">
          {{ $t("commons.button.add")
          }}{{ $t("business.access_control.object") }}
        </el-button>
      </ko-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
import {
  ClusterRole,
  Role,
  RoleRef,
  ServiceAccount,
  Subject,
  useK8SApi
} from "../../../api/k8s";
import { onMounted, ref } from "vue";
import { checkPermissions } from "../../../utils/permission";
// import { listClusterRoles } from "@/api/clusterroles";
// import { listNamespaceRoles } from "@/api/roles";
// import { getNamespaces } from "@/api/auth";
// import { listServiceAccountsWithNs } from "@/api/serviceaccounts";
// import { checkPermissions } from "@/utils/permission";

const { clusterRoleRepo, serviceAccountRepo, roleRepo, namespaceRepo } =
  useK8SApi();

type Prop = {
  clusterName: string;
  namespace: string;
  roleRefObj: RoleRef;
  subjectArray: any;
};

const props = defineProps<Prop>();
const emit = defineEmits(["update:roleRefObj", "update:subjectArray"]);
const roleRef = ref<RoleRef>({
  kind: "ClusterRole",
  apiGroup: "rbac.authorization.k8s.io",
  name: ""
});

const editForm = ref({
  subjects: []
});

const roles = ref<(Role | ClusterRole)[]>([]);
const namespaces = ref([]);
const serviceAccountList = ref<ServiceAccount[][]>([
  [{ metadata: { name: "" } }]
]);
const loading = ref(false);

const onRoleRefKindChanged = async (kind?: string) => {
  roles.value = [];
  roleRef.value.name = "";
  if (kind === "Role") {
    const nsPermission = await checkPermissions({
      scope: "namespace",
      apiGroup: "rabc.authorization.k8s.io",
      resource: "roles",
      verb: "list"
    });

    if (nsPermission) {
      roleRepo
        .listNamespaceRoles(props.clusterName, props.namespace)
        .then(res => {
          roles.value = res.items;
        });
    } else {
      clusterRoleRepo.listClusterRoles(props.clusterName).then(res => {
        roles.value = res.items;
      });
    }
  }
};

const onRemoveSubject = (index: number) => {
  serviceAccountList.value.splice(index, 1);
  editForm.value.subjects.splice(index, 1);
};

const onAddSubject = () => {
  serviceAccountList.value.push([]);
  editForm.value.subjects.push({
    kind: "",
    name: ""
  });
};

const onSubjectKindChanged = (data: Subject) => {
  if (data.kind === "ServiceAccount") {
    data.namespace = "";
    delete data.apiGroup;
  }
  if (data.kind === "User" || data.kind === "Group") {
    data.apiGroup = "rbac.authorization.k8s.io";
    delete data.namespace;
  }
};

const onNamespaceChange = async (data: Subject, index: number) => {
  loading.value = true;
  const nsPermission = await checkPermissions({
    scope: "namespace",
    apiGroup: "rabc.authorization.k8s.io",
    resource: "serviceaccounts",
    verb: "list"
  });

  if (nsPermission) {
    const { items } = await serviceAccountRepo.listServiceAccountsWithNs(
      props.clusterName,
      data.namespace
    );

    serviceAccountList.value[index] = items;
    loading.value = false;
  }
};

onMounted(() => {
  namespaceRepo
    .getNamespaceList({ clusterName: props.clusterName })
    .then(res => {
      if (res && res.items) {
        namespaces.value = res.items;
      }
    });

  onRoleRefKindChanged(props.roleRefObj.kind);
  if (props.roleRefObj) {
    roleRef.value = props.roleRefObj;
  } else {
    emit("update:roleRefObj", roleRef.value);
  }

  if (props.subjectArray) {
    editForm.value.subjects = props.subjectArray;
  } else {
    emit("update:subjectArray", editForm.value.subjects);
  }
});
</script>

<style scoped></style>
